package com.miku.sys.services;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.miku.common.BaseServiceImpl;
import com.miku.db.sys.entity.SysUser;
import com.miku.sys.dao.SysUserDaoI;
import com.miku.sys.security.realm.LcUsernamePasswordToken;
import com.miku.sys.utils.UserUtils;
import com.miku.utils.StringUtils;

@Service
@Transactional
public class SystemUserServiceImpl extends BaseServiceImpl implements SystemUserServiceI {
	
	@Autowired SysUserDaoI userDao;
	
	//用户注册
	@Override
	public void register(HttpServletRequest request, String loginName, String password ,String nickname) {
		//添加用户
		SysUser u = new SysUser();
		u.setLoginName(loginName);
		u.setNickname(nickname);
		u.setPassword(UserUtils.entryptPassword(password));
		u.setCreateTime(new Date());
		userDao.merge(u);
		//自动登录
		String username = u.getLoginName();
		boolean rememberMe = true;
		String host = StringUtils.getRemoteAddr(request);
		String captcha = null;
		boolean mobile = false;
		
		Subject currentUser = UserUtils.getSubject();
		try{
			currentUser.login(new LcUsernamePasswordToken(
					u, username, "", rememberMe, host, captcha, mobile));
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	//验证注册邮箱是否存在（存在为true，不存在为false）
	@Override
	public boolean isExistsEmail(String email) {
		int emailCount = userDao.isExistsEmail(email);
		return emailCount == 0 ? false : true ;
	}
}
